package cn.outsourcing.supermarket.service.impl;

import cn.outsourcing.supermarket.common.constants.CommonConstants;
import cn.outsourcing.supermarket.common.exception.SupermarketException;
import cn.outsourcing.supermarket.common.utils.JwtUtils;
import cn.outsourcing.supermarket.converter.HiolabsUserConverter;
import cn.outsourcing.supermarket.dto.UserDetailDTO;
import cn.outsourcing.supermarket.mapper.HiolabsSettingsMapper;
import cn.outsourcing.supermarket.mapper.HiolabsUserMapper;
import cn.outsourcing.supermarket.po.HiolabsSettings;
import cn.outsourcing.supermarket.po.HiolabsUser;
import cn.outsourcing.supermarket.service.HiolabsSettingsService;
import cn.outsourcing.supermarket.vo.UserDetailVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 设置服务实现类
 *
 * @author gzkemays
 * @since 2021-10-21
 */
@Service
public class HiolabsSettingsServiceImpl extends ServiceImpl<HiolabsSettingsMapper, HiolabsSettings>
    implements HiolabsSettingsService {
  @Resource HiolabsSettingsMapper settingsMapper;
  @Resource HiolabsUserMapper userMapper;
  @Resource HttpServletRequest request;

  @Override
  public HiolabsSettings getSettings() {
    return null;
  }

  @Override
  public UserDetailVO getUserDetail() {
    Integer userId =
        (Integer) JwtUtils.getTokenClaimByRequest(request, CommonConstants.TOKEN_USER_ID_KEY);
    HiolabsUser user = userMapper.selectById(userId);
    UserDetailVO userDetailVO = HiolabsUserConverter.INSTANCE.convertToUserDetail(user);
    userDetailVO.setIntegral(user.getCredits());
    return userDetailVO;
  }

  @Override
  public UserDetailVO saveUserDetail(UserDetailDTO dto) {
    Integer userId =
        (Integer) JwtUtils.getTokenClaimByRequest(request, CommonConstants.TOKEN_USER_ID_KEY);
    HiolabsUser user = userMapper.selectById(userId);
    if (user != null) {
      user.setName(dto.getName());
      user.setMobile(dto.getMobile());
      userMapper.updateById(user);
      UserDetailVO vo = HiolabsUserConverter.INSTANCE.convertToUserDetail(user);
      vo.setIntegral(user.getCredits());
      return HiolabsUserConverter.INSTANCE.convertToUserDetail(user);
    }
    throw new SupermarketException(CommonConstants.REQUEST_FAIL_CODE, "没有该对象");
  }
}
